<template>
  <!-- page-meta伪html标签，解决rem随html根元素字体大小问题，因为小程序中没有html元素 -->

  <!-- #ifndef H5 -->
  <!-- 解决H5端因为加了<page-meta>元素无法识别导致无法渲染元素问题 -->
  <page-meta root-font-size="52px">
    <!-- #endif -->
    <view class="detail-container">
      <!-- 文章内容区域 -->
      <block v-if="articleData !== null">
        <!-- 标题 -->
        <view class="title">{{ articleData.articleTitle }}</view>
        <view class="detail-info">
          <view class="detail-left">
            <view class="avatar-box">
              <!-- 头像 -->
              <image class="avatar" :src="articleData.avatar"></image>
            </view>
            <view class="author-box">
              <!-- 作者 -->
              <text class="author">{{ articleData.nickName }}</text>
              <!-- 发布时间 -->
              <text class="release-time">{{ articleData.date }}</text>
            </view>
          </view>
          <view class="detail-right">
            <!-- 关注按钮 -->
            <button
              class="follow"
              :type="articleData.isFollow ? 'primary' : 'default'"
              size="mini"
              :loading="isFollowLoading"
              @click="onFollowClick"
            >
              {{ articleData.isFollow ? '已关注' : '关注' }}
            </button>
          </view>
        </view>
        <!-- 文章内容 -->
        <!-- <rich-text :nodes="articleData.content"></rich-text> -->
        <!-- scroll-table	：是否给每个表格添加一个滚动层使其能单独横向滚动 -->
        <mp-html class="markdown_views" :content="addClassFromHTML(articleData.content)" scroll-table />
        <!-- 文章评论 -->
        <view class="comment-box" style="margin-bottom: 79px">
          <!-- 1. 给 mescroll-body 的组件添加：ref="mescrollItem"（mescrollItem 是固定的不可以变化） -->
          <article-comment-list ref="mescrollItem" :articleId="articleId"></article-comment-list>
        </view>
      </block>
      <!-- 底部功能区 -->
      <article-operate @commitClick="onCommitClick" :articleData="articleData"></article-operate>
      <!-- 输入评论弹窗 popup -->
      <uni-popup ref="popup" type="bottom" @change="onCommitPopupChange">
        <article-comment-commit
          v-if="isShowCommit"
          :articleId="articleId"
          @success="onSendSuccess"
        ></article-comment-commit>
      </uni-popup>
    </view>
    <!-- #ifndef H5 -->
  </page-meta>
  <!-- #endif -->
</template>

<script>
import mpHtml from '@/uni_modules/mp-html/components/mp-html/mp-html'
import { _getArticleDetail } from '../../../api/article'
// 2. 引入 mescroll-comp.js
import MescrollCompMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mixins/mescroll-comp.js'
import ArticleOperate from '../../../components/article-operate/article-operate.vue'
import isLogin from '../../../mixin/isLogin'
import { _userFollow } from '../../../api/user'
export default {
  // 3. 注册 mixins
  mixins: [MescrollCompMixin, isLogin],
  data() {
    return {
      author: '', //作者名 （列表中的 author \|\| user_name）
      articleId: '', // id（列表中的 id）
      articleData: null, // 文章详情数据
      isFollowLoading: false,
      isShowCommit: false // popup的显示状态
    }
  },
  components: {
    mpHtml,
    ArticleOperate
  },
  onLoad(options) {
    console.log(options, '文章详情')
    this.author = options.author
    this.articleId = options.articleId
    this.getArticleDetail()
  },
  methods: {
    /**
     * 请求文章详情
     */
    async getArticleDetail() {
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      const { data } = await _getArticleDetail({ author: this.author, articleId: this.articleId })
      this.articleData = data
      console.log(this.articleData)
    },
    /**
     *  为所有的 DOM 增加类名
     */
    addClassFromHTML(info) {
      // 先替换 blockquote
      return info
        .replace(/<p>/gi, '<p class="p-cls">')
        .replace(/<a>/gi, '<a class="a-cls">')
        .replace(/<h1>/gi, '<h1 class="h1-cls">')
        .replace(/<h2>/gi, '<h2 class="h2-cls">')
        .replace(/<h3>/gi, '<h3 class="h3-cls">')
        .replace(/<h4>/gi, '<h4 class="h4-cls">')
        .replace(/<h5>/gi, '<h5 class="h5-cls">')
        .replace(/<h6>/gi, '<h6 class="h6-cls">')
        .replace(/<ul>/gi, '<ul class="ul-cls">')
        .replace(/<li>/gi, '<li class="li-cls">')
        .replace(/<ol>/gi, '<ol class="ol-cls">')
        .replace(/<td>/gi, '<td class="td-cls">')
        .replace(/<th>/gi, '<th class="th-cls">')
        .replace(/<tr>/gi, '<tr class="tr-cls">')
        .replace(/<dl>/gi, '<dl class="dl-cls">')
        .replace(/<dd>/gi, '<dd class="dd-cls">')
        .replace(/<hr>/gi, '<hr class="hr-cls">')
        .replace(/<pre>/gi, '<pre class="pre-cls">')
        .replace(/<strong>/gi, '<strong class="strong-cls">')
        .replace(/<input>/gi, '<input class="input-cls">')
        .replace(/<table>/gi, '<table class="table-cls">')
        .replace(/<details>/gi, '<details class="details-cls">')
        .replace(/<code>/gi, '<code class="code-cls">')
        .replace(/<kbd>/gi, '<kbd class="kbd-cls">')
        .replace(/<summary>/gi, '<summary class="summary-cls">')
        .replace(/<blockquote>/gi, '<blockquote class="blockquote-cls">')
        .replace(/<img/gi, '<img class="img-cls"')
    },
    /**
     * 点击关注判定是否登录
     */
    async onFollowClick() {
      const result = await this.isLogin()
      if (!result) return
      // 开启 button 的 loading
      this.isFollowLoading = true

      await _userFollow({ author: this.author, isFollow: !this.articleData.isFollow })
      // 修改用户数据
      this.articleData.isFollow = !this.articleData.isFollow
      console.log(this.articleData.isFollow)
      // 关闭 button 的 loading
      this.isFollowLoading = false
    },
    /**
     * 发表评论
     */
    onCommitClick() {
      // 通过组件定义的ref调用uni-popup方法
      this.$refs.popup.open()
    },
    /**
     * 监听popup change	组件状态发生变化触发	e={show: true｜false,type:当前模式}
     */
    onCommitPopupChange(e) {
      // 解决输入框关闭内容还存在的问题，因为article-comment-commit没有销毁
      if (e.show) {
        this.isShowCommit = e.show
      } else {
        // 修改对应的标记，当 popup 关闭时，为了动画平顺，进行延迟处理
        setTimeout(() => {
          this.isShowCommit = e.show
        }, 200)
      }
    },
    /**
     * 发表成功
     */
    onSendSuccess(data) {
      // 关闭popup弹出层
      this.$refs.popup.close()
      this.isShowCommit = false
      this.$refs.mescrollItem.addCommentList(data)
    }
  }
}
</script>

<style lang="scss">
.detail-container {
  padding: $uni-spacing-col-base $uni-spacing-row-base;
  .title {
    font-size: $uni-font-size-title;
    color: $uni-text-color-title;
    font-weight: bold;
  }
  .detail-info {
    padding: $uni-spacing-col-base 0;
    display: flex;
    justify-content: space-between;

    .detail-left {
      display: flex;
      .author-box {
        margin-left: $uni-spacing-row-base;
        display: flex;
        flex-direction: column;
        .author {
          font-size: $uni-font-size-base;
          font-weight: bolder;
          color: $uni-color-title;
        }
        .release-time {
          font-size: $uni-font-size-sm;
          color: $uni-text-color-grey;
        }
      }
    }

    .detail-right {
      display: flex;
      align-items: center;
    }
  }
}
</style>
